package com.asyf.demo.controller;

import com.asyf.demo.service.DownloadService;
import com.asyf.demo.demo.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author yjz
 * @Date 2021/8/16 15:43
 */
@RestController
@Api(tags = "下载模块")
@RequestMapping(value = "/download")
public class DownloadController {

    @Autowired
    private DownloadService downloadService;

    @GetMapping("/downloadExcel")
    @ApiOperation(value = "下载excel模板", notes = "easypoi")
    public void downloadExcel(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String path = "/templates/2250.xlsx";
        String fileName = "模板" + path.substring(path.lastIndexOf("/") + 1);
        downloadService.downloadExcel(response, path, fileName);
    }

    @GetMapping("/downloadAndEdit")
    @ApiOperation(value = "poi下拉选项", notes = "easypoi")
    public void downloadAndEdit(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String path = "/templates/2250.xlsx";
        String fileName = "模板" + path.substring(path.lastIndexOf("/") + 1);
        downloadService.downloadAndEdit(response, path, fileName);
    }

    //Java 将List＜Map＜String, Object＞＞导出为excel
    //http://localhost:8080/download/downloadFromMap
    @GetMapping("/downloadFromMap")
    @ApiOperation(value = "将List＜Map＜String, Object＞＞导出为excel", notes = "poi")
    public void downloadFromMap(HttpServletResponse response, HttpServletRequest request) throws Exception {
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("姓名", i);
            map.put("年龄", i);
            map.put("性别", i);
            list.add(map);
        }
        try (HSSFWorkbook workbook = ExcelUtil.createExcel(list); OutputStream outputStream = ExcelUtil.getOutputStream(response, "excel测试文件.xlsx")) {
            workbook.write(outputStream);
        }
    }


}
